#!/usr/bin/env bash

# 项目名称
JOB_NAME=jobName
# jar 名
JAR_NAME=jarName
# 镜像名
IMAGE_NAME=imageName
# 容器名CONTAINER_NAMES = ("name1" "name2" "name3" ...)
CONTAINER_NAMES=("name1" "name2" "name3")
# 网桥名（不设置使用默认网桥）
NETWORK_NAME=networkName
# 服务端口
SERVER_PORT=100
# 端口映射 (宿主机端口:容器内端口)
PORTS=("100:$SERVER_PORT","101:$SERVER_PORT","102:$SERVER_PORT")


cd /

# 停止项目并晴空目录
if [ ! -d "/usr/local/docker/$JOB_NAME" ];
then
  #   这是个新的项目创建目录
  mkdir -p "/usr/local/docker/$JOB_NAME"

else
  #   对于已存在的项目先停止
  cd  /usr/local/docker/$JOB_NAME
  docker-compose  down
  rm -rf *
fi

# 删除所有容器
for(( i=0;i<${#CONTAINER_NAMES[@]};i++)) do

docker rm ${CONTAINER_NAMES[i]}

done;

# 删除镜像
docker rmi $IMAGE_NAME

# 移动文件
mv /$JAR_NAME /usr/local/docker/$JOB_NAME/

# Dockerfile
cat > Dockerfile << EOF

FROM primetoninc/jdk:1.8
RUN mkdir $JOB_NAME
WORKDIR  $JOB_NAME
ADD $JAR_NAME .

RUN echo "#!/bin/bash" > run.sh
RUN echo "/usr/local/jdk1.8.0_152/bin/java  -jar  $JAR_NAME" >> run.sh
RUN chmod a+x run.sh
CMD ["./run.sh"]

EOF

# 创建镜像
docker build -t $IMAGE_NAME .

# docker-compose

cat > docker-compose.yml << EOF

version: '3.1'
services:
EOF


# 删除所有容器
for(( i=0;i<${#CONTAINER_NAMES[@]};i++)) do
cat >> docker-compose.yml << EOF
  ${CONTAINER_NAMES[i]}:
    image: $IMAGE_NAME
    container_name: ${CONTAINER_NAMES[i]}
    ports:
      - ${PORTS[i]}
    environment:
      SERVER_PORT: $SERVER_PORT
      HOSTNAME: ${CONTAINER_NAMES[i]}
    networks:
      - $NETWORK_NAME

EOF

done;

cat >> docker-compose.yml << EOF
networks:
  $NETWORK_NAME:
    external: true
EOF

docker-compose up -d